package com.yoomiito.app.share.ui;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.zxing.WriterException;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.adapter.goods.share.GoodsPicShareAdapter;
import com.yoomiito.app.listener.OnSelectedChangeListener;
import com.yoomiito.app.model.bean.GoodsShareInfo;
import com.yoomiito.app.model.bean.SharePicInfo;
import com.yoomiito.app.model.config.ConfigInfo;
import com.yoomiito.app.share.presenter.SharePresenter;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.ImageLoader;
import com.yoomiito.app.utils.ImageUtils;
import com.yoomiito.app.utils.SpannableUtils;
import com.yoomiito.app.utils.TouchUtils;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.wx.WXShareMultiImageHelper;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.utils.ZxingUtil;
import com.yoomiito.app.utils.wx.UMengShareUtils;
import com.yoomiito.app.widget.GridItemDecoration;
import com.yoomiito.app.widget.ImageView1_1;
import com.yoomiito.app.widget.MyItemDecoration;
import com.yoomiito.app.widget.SelectView;
import com.yoomiito.app.widget.dialog.ShareDialog;
import com.yoomiito.app.widget.ShareDocVIew;
import com.yoomiito.app.widget.state.ContentType;
import com.yoomiito.app.widget.state.EmptyType;
import com.yoomiito.app.widget.state.StatusManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.droidlover.xdroidmvp.cache.SharedPref;

public class GoodsShareActivity extends BaseActivity<SharePresenter> implements OnSelectedChangeListener, View.OnClickListener {
    //    @BindView(R.id.act_share_doc)
    ShareDocVIew mShareDocVIew;
    //    @BindView(R.id.act_share_iv)
    ImageView iv;
    //    @BindView(R.id.act_share_rcy)
    RecyclerView rcy;
    //    @BindView(R.id.act_share_ad)
    SelectView mSelectView;

    @BindView(R.id.tv_center)
    TextView titleTv;
    @BindView(R.id.frameLayout)
    FrameLayout mFrameLayout;


    private List<SharePicInfo> picInfos = new ArrayList<>();
    private GoodsPicShareAdapter goodsPicShareAdapter;
    private ImageView1_1 mGoodsPic;
    private String id;
    private View view;
    private ImageView erWeiMaIv;
    private List<String> urls;
    private Bitmap bitmap;
    private boolean isDownloadAd = true;
    private int type;
    private int mGoodsType;
    private TextView mGoodsTitleTv;
    private TextView mGoodsPriceTv;
    private TextView mGoodsOldPriceTv;
    private TextView mGoodsSaleSizeTv;
    private int mGoodsType_1;
    private GridLayoutManager gridLayoutManager;
    private TextView mCouponTv;
    private LinearLayout mCouponLl;
    private String mShareUrl;
    private ShareDialog shareDialog;
    private ConfigInfo mConfigInfo;
    private String WXEventId = "";
    private String WXCircleEventId = "";
    private String AlbumEventId = "";
    private String mShareText = "";

    @Override
    public int getLayoutId() {
        return R.layout.act_share;
    }

    @Override
    public SharePresenter newP() {
        return new SharePresenter(App.mAppConfig);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        String config = SharedPref.getInstance(this).getString(Constant.Config, "");
        if (!TextUtils.isEmpty(config)) {
            mConfigInfo = JSON.parseObject(config, ConfigInfo.class);
        } else {
            showLoading();
            getP().getConfig();
        }
        mStatusManager = new StatusManager.Builder(this)
                .addType(new ContentType(R.layout.item_share))
                .addType(new EmptyType().setEmptyContent("加载数据失败"))
                .build();
        mShareDocVIew = mStatusManager.view().findViewById(R.id.act_share_doc);
        iv = mStatusManager.view().findViewById(R.id.act_share_iv);
        rcy = mStatusManager.view().findViewById(R.id.act_share_rcy);
        mSelectView = mStatusManager.view().findViewById(R.id.act_share_ad);
        mStatusManager.view().findViewById(R.id.item_share_wx).setOnClickListener(this);
        mStatusManager.view().findViewById(R.id.item_share_dynamic).setOnClickListener(this);
        mStatusManager.view().findViewById(R.id.item_share_photo).setOnClickListener(this);
        mFrameLayout.addView(mStatusManager.view());

        id = getIntent().getStringExtra(Constant.ID);
        mGoodsType = getIntent().getIntExtra(Constant.TYPE, AllCode.TaoBao);
        titleTv.setVisibility(View.VISIBLE);
        titleTv.setText("创建分享");
        mSelectView.setChangeListener(this);
        switch (mGoodsType) {
            case AllCode.TaoBao:
                initTaoBaoPic();
                mGoodsType_1 = 1;
//                mShareUrl = NetUrl.TaoBaoGoodsInfoUrl;
//                mShareUrl = mConfigInfo == null ? NetUrl.TaoBaoGoodsInfoUrl : mConfigInfo.getRe_tao_url().getValue() + NetUrl.TaoBaoGoodsInfoUrl_1;
                break;
            case AllCode.Gift:
            case AllCode.BaoPin:
            case AllCode.YouPin:
            case AllCode.AgentMall:
            case AllCode.StarStore:
                initGiftPic();
//                mShareUrl = NetUrl.GiftGoodsInfoUrl;
//                mShareUrl = mConfigInfo == null ? NetUrl.GiftGoodsInfoUrl : mConfigInfo.getRe_ym_url().getValue() + NetUrl.GiftGoodsInfoUrl_1;

                mGoodsType_1 = 2;
                mShareDocVIew.setVisibility(View.GONE);
                break;
        }
        //埋点事件id
        switch (mGoodsType) {
            case AllCode.TaoBao:
                WXEventId = "taobaoProductCreateShareToWechat";
                WXCircleEventId = "taobaoProductCreateShareToWechatMoment";
                AlbumEventId = "taobaoProductCreateShareToAlbum";
                break;
            case AllCode.Gift:
                WXEventId = "giftProductCreateShareToWechat";
                WXCircleEventId = "giftProductCreateShareToWechatMoment";
                AlbumEventId = "giftProductCreateShareToAlbum";
                break;
            case AllCode.BaoPin:
                WXEventId = "hotProductCreateShareToWechat";
                WXCircleEventId = "hotProductCreateShareToWechatMoment";
                AlbumEventId = "hotProductCreateShareToAlbum";
                break;
        }


        initShareTheme();
        getP().getShareInfo(id, mGoodsType_1);
    }

    /**
     * 初始化礼包商品广告图
     */
    private void initGiftPic() {
        view = LayoutInflater.from(this).inflate(R.layout.gift_share_pic_1, null);
        mGoodsPic = view.findViewById(R.id.gift_share_pic_goods_iv);
        erWeiMaIv = view.findViewById(R.id.gift_share_pic_erweima);
        mGoodsTitleTv = view.findViewById(R.id.gift_share_pic_goods_title);
        mGoodsPriceTv = view.findViewById(R.id.gift_share_pic_goods_price);
        mGoodsOldPriceTv = view.findViewById(R.id.gift_share_pic_goods_old_price);
        mGoodsSaleSizeTv = view.findViewById(R.id.gift_share_pic_sale_size);
//        ImageUtils.layoutView(view);
    }

    /**
     * 初始化淘宝商品广告图
     */
    private void initTaoBaoPic() {
        view = LayoutInflater.from(this).inflate(R.layout.taobao_share_pic_1, null);
        mGoodsPic = view.findViewById(R.id.taobao_share_pic_goods_iv);
        erWeiMaIv = view.findViewById(R.id.share_pic_erweima);
        mGoodsTitleTv = view.findViewById(R.id.taobao_share_pic_goods_title);
        mGoodsPriceTv = view.findViewById(R.id.taobao_share_pic_goods_price);
        mGoodsOldPriceTv = view.findViewById(R.id.taobao_share_pic_goods_old_price);
        mGoodsSaleSizeTv = view.findViewById(R.id.taobao_share_pic_sale_size);
        mCouponTv = view.findViewById(R.id.share_pic_coupon_value);
        mCouponLl = view.findViewById(R.id.share_pic_coupon_ll);
//        ImageUtils.layoutView(view);
    }

    //初始化主题
    private void initShareTheme() {
        rcy.addItemDecoration(new MyItemDecoration(this, RecyclerView.VERTICAL));
        if (gridLayoutManager == null) {
            gridLayoutManager = new GridLayoutManager(this, 2);
        }
        rcy.setLayoutManager(gridLayoutManager);
        rcy.addItemDecoration(new GridItemDecoration(5));
        goodsPicShareAdapter = new GoodsPicShareAdapter(picInfos);
        goodsPicShareAdapter.setOnShowPicChange(url -> makeThemePic(url));
        rcy.setAdapter(goodsPicShareAdapter);
    }

    /**
     * 生成二维码
     *
     * @param shareUrl
     */
    private void makeErWM(String shareUrl) {
//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.app_launcher, null);
        try {
            erWeiMaIv.setImageBitmap(ZxingUtil.cretaeZxing(shareUrl, getResources().getColor(R.color.color_black)));
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    //生成广告图
    private void makeThemePic(String picUrl) {
        RequestOptions options = new RequestOptions();
        if (mGoodsType == AllCode.Gift) {
            RoundedCorners corners = new RoundedCorners(12);
            options = RequestOptions.bitmapTransform(corners);
        }
        Glide.with(this).asBitmap().apply(options).load(picUrl).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                switch (mGoodsType) {
                    case AllCode.TaoBao:
                        mGoodsPic.setImageBitmap(resource);
                        break;
                    case AllCode.Gift:
                    case AllCode.BaoPin:
                    case AllCode.YouPin:
                    case AllCode.AgentMall:
                    case AllCode.StarStore:
                        mGoodsPic.setImageBitmap(resource);
                        break;
                }
                if (goodsPicShareAdapter.getBitmaps().contains(bitmap)) {
                    goodsPicShareAdapter.getBitmaps().remove(bitmap);
                }
                bitmap = ImageUtils.viewSaveToImage(view);

                iv.setImageBitmap(bitmap);
//                mSelectView.setSelect(true);
            }
        });
    }

    //设置数据
    //备注：商品title超过两行 超过21个字 可以完整显示
    //这个跟ConstraintLayout布局有关系 1行时其高度丢失 在布局预览中可见到
    //换成Linearlayout则不会出现
    public void setData(GoodsShareInfo goodsShareInfo) {
        if (goodsShareInfo.getSmall_images() == null) {
            urls = new ArrayList<>();
        } else {
            urls = goodsShareInfo.getSmall_images().getString();
        }
        urls.add(goodsShareInfo.getPict_url());
        mShareText = goodsShareInfo.getTitle();
//        urls.add("https://img.alicdn.com/i2/3586740366/TB2XEX4m8TH8KJjy0FiXXcRsXXa_!!3586740366.jpg");
        mGoodsTitleTv.setText(goodsShareInfo.getTitle());
        mGoodsPriceTv.setText(SpannableUtils.getDiscountPrice(
                "¥" +
                        SpannableUtils.handlePrice(goodsShareInfo.getPrice()) +
                        (mGoodsType == AllCode.TaoBao ? "券后" : "专享")
                , R.color.color_balk_333333)
        );
        String marketPrice = mGoodsType == AllCode.TaoBao ? goodsShareInfo.getZk_final_price() : goodsShareInfo.getReserve_price();
        mGoodsOldPriceTv.setText(SpannableUtils.getSpannable(
                (mGoodsType == AllCode.TaoBao ? "淘宝原价" : "原价") + SpannableUtils.handlePrice(marketPrice), 0));//goodsShareInfo.getReserve_price()
        if (SpannableUtils.isEmptyOr0(marketPrice)) {
            mGoodsOldPriceTv.setVisibility(View.GONE);
        }
        mGoodsSaleSizeTv.setText((mGoodsType == AllCode.TaoBao ? "月销" : "销量") + SpannableUtils.saleNum(goodsShareInfo.getVolume()));
        if (AllCode.TaoBao == mGoodsType) {
            if (SpannableUtils.isEmptyOr0(goodsShareInfo.getCoupon_price())) {
                mCouponLl.setVisibility(View.GONE);
            } else {
                mCouponTv.setText("¥" + SpannableUtils.handlePrice(goodsShareInfo.getCoupon_price()));
            }
        }
        ImageUtils.layoutView(view);
//        switch (mGoodsType) {
//            case AllCode.TaoBao:
//                mShareUrl += "id=" + id + "&shareUserId=" + UserInfoConfig.getUserId();
//                break;
//            case AllCode.BaoPin:
//            case AllCode.Gift:
//            case AllCode.YouPin:
//                mShareUrl += "id=" + id;
//                break;
//        }

        makeErWM(goodsShareInfo.getShare_url());
        makeThemePic(urls.get(0));
        mSelectView.setSelect(true);

        for (int i = 0; i < urls.size(); i++) {
            SharePicInfo info = new SharePicInfo();
            info.setPicUrl(urls.get(i));
            info.setShowPic(i == 0 ? true : false);
            picInfos.add(info);
        }
        goodsPicShareAdapter.notifyDataSetChanged();
        List<String> strings = new ArrayList<>();
        strings.add(goodsShareInfo.getTitle());
        strings.add("【原价】:" + goodsShareInfo.getZk_final_price());
        strings.add("【券后价】：" + goodsShareInfo.getPrice());
        strings.add("【下单地址】：" + goodsShareInfo.getShort_url());
        strings.add("【分享赚钱】:" + goodsShareInfo.getGet_money());
        strings.add("【邀请码】：" + UserInfoConfig.getInviteCode());
        strings.add("【淘口令】：" + goodsShareInfo.getTkl_code());
        mShareDocVIew.setText(strings);
        dismissLoading();
    }

    @OnClick({R.id.iv_back_left})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back_left:
                finish();
                break;
            case R.id.item_share_wx:
                TouchUtils.onEvent(WXEventId, UserInfoConfig.getRoleId(), UserInfoConfig.getAgent());
                type = 1;
                AllUtils.copyText(this, mShareText);
                if (Build.VERSION.SDK_INT >= 23) {
                    requestPermission();
                } else {
                    wxShare();
                }
                break;
            case R.id.item_share_dynamic:
                TouchUtils.onEvent(WXCircleEventId, UserInfoConfig.getRoleId(), UserInfoConfig.getAgent());
                type = 2;
                if (AllCode.TaoBao == mGoodsType) {
                    mShareText = mShareDocVIew.getContent();
                }
                AllUtils.copyText(this, mShareText);
                YMToast.showText("复制商品分享文案成功");
                List<Bitmap> bitmaps = getShareBitmaps();
                if (bitmaps.size() == 1) {
                    UMengShareUtils.shareWXPic(SHARE_MEDIA.WEIXIN_CIRCLE, GoodsShareActivity.this, bitmaps.get(0));
                    return;
                }
                savePhoto();
                if (shareDialog == null) {
                    shareDialog = new ShareDialog(this);
                }
                shareDialog.show();
                break;
            case R.id.item_share_photo:
                TouchUtils.onEvent(AlbumEventId, UserInfoConfig.getRoleId(), UserInfoConfig.getAgent());
                type = 3;
                savePhoto();
                break;
        }
    }

    public void requestPermission() {
        AllUtils.requestPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(aBoolean -> {
                    switch (type) {
                        case 1:
                            wxShare();
                            break;
                        case 2:
                        case 3:
                            if (aBoolean) loadPic();
                            break;
                    }

                });
    }

    private void savePhoto() {
        if (!isDownloadAd & (goodsPicShareAdapter.getUrls() != null && goodsPicShareAdapter.getUrls().size() == 0)) {
            Toast.makeText(context, "请选择图片", Toast.LENGTH_SHORT).show();
            return;
        }
        if (Build.VERSION.SDK_INT >= 23) {
            requestPermission();
        } else {
            loadPic();
        }
    }

    private void loadPic() {
        if (goodsPicShareAdapter.getUrls() != null && goodsPicShareAdapter.getUrls().size() > 0) {
            ImageLoader.getInstance().downloadPic(GoodsShareActivity.this, goodsPicShareAdapter.getUrls());
        }
        if (isDownloadAd) {
            ImageLoader.getInstance().downloadPic(GoodsShareActivity.this, bitmap);
        }
        Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
    }

    private void wxShare() {
        String text = "";
        if (AllCode.TaoBao == mGoodsType) {
            text = mShareDocVIew.getContent();
        }
//        List<Bitmap> bitmaps = goodsPicShareAdapter.getBitmaps();
//        if (isDownloadAd && !bitmaps.contains(bitmap))
//            bitmaps.add(bitmap);
        List<Bitmap> bitmaps = getShareBitmaps();
        if (bitmaps.size() == 0) {
            Toast.makeText(context, "请选择图片", Toast.LENGTH_SHORT).show();
            return;
        }
        WXShareMultiImageHelper.shareToSession(this, bitmaps, text);
    }

    private List<Bitmap> getShareBitmaps() {
        List<Bitmap> bitmaps = goodsPicShareAdapter.getBitmaps();
        if (isDownloadAd && !bitmaps.contains(bitmap))
            bitmaps.add(bitmap);
        return bitmaps;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    public void change(View view, boolean isSelected) {
        isDownloadAd = isSelected;
    }

    @Override
    protected void onDestroy() {
        if (goodsPicShareAdapter != null) goodsPicShareAdapter.clearBitmap();
        bitmap = null;
        super.onDestroy();
    }
}
